import random
import re

from django import http
from django.contrib.auth import logout
from django.http import HttpResponse
# from django.shortcuts import render
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from utils import constants
from utils.response_code import RETCODE


class IndexView(View):
    def get(self, request):
        """
        主页
        :param request:
        :return:
        """
        # return HttpResponse("我是 主页 ....")
        return render(request, 'index.html')


class PasswordView(View):
    def get(self, request):
        return render(request, 'password.html')

    def post(self, request):
        mobile = request.POST.get('mobile')
        redis_conn = get_redis_connection('code')
        redis_conn1 = get_redis_connection('mobile')
        redis_conn1.set(mobile, mobile)

        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 保存短信验证码
        redis_conn.setex('%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 为了在测试期间减少短信发送，可以屏蔽发送短信功能，使用打印的方式来获取到真正的验证码值
        # 发送短信验证码
        print(mobile)
        # send_sms(mobile, sms_code)
        print(">>>>短信验证码>>>>>>", sms_code)
        # content = {
        #     'mobile': mobile
        # }
        # print(data)
        # return render(request, 'password2.html', {'content': content})
        # 响应结果
        response = http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '发送成功'})
        #
        return response


class Password2View(View):
    def get(self, request):
        return render(request, 'password2.html')

    def post(self, request):
        code = request.POST.get('code')
        redis_conn = get_redis_connection('mobile')
        print(code)
        try:
            mobile = redis_conn.randomkey()
            # mobile = mobile[1]
            mobile = mobile.decode()
            print(mobile)
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '手机号不存在'})

        redis_conn = get_redis_connection('code')
        sms_code_saved = redis_conn.get('%s' % mobile)
        print(sms_code_saved)
        if sms_code_saved is None:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '无效的短信验证码'})
        if code != sms_code_saved.decode():
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '输入的短信验证码有误'})

        return http.JsonResponse({'errno': RETCODE.OK})


class Password3View(View):
    def get(self, request):
        return render(request, 'password3.html')

    def post(self, request):
        '''实现修改密码逻辑'''

        # 接收参数
        old_password = request.POST.get('old_password')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        # 验证参数
        # if not all([old_password, new_password, new_password2]):
        #     return http.HttpResponseForbidden('缺少必传参数')
        # if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
        #     return http.HttpResponseBadRequest('密码最少8位，最长20位')
        # if new_password != new_password2:
        #     return http.HttpResponseBadRequest('两次输入的密码不一致')
        if not all([old_password, password, password2]):
            # return http.HttpResponseForbidden('缺少必传参数')
            print(4444444444444444)
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '缺少必传参数'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '密码最少8位，最长20位'})
        if password != password2:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '两次输入的密码不一致'})
        # 检验旧密码是否正确
        if not request.user.check_password(old_password):
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '原始密码错误'})
        # 更新新密码
        try:
            request.user.set_password(password)
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '修改密码失败'})

        # 退出登录，删除登录信息
        logout(request)
        # 跳转到登录页面
        response = redirect(reverse('users:login'))

        response.delete_cookie('username')

        return response
